package com.appkubes.mall.restful.config;

import com.alibaba.fastjson.JSONObject;
import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.mall.core.entity.MallOrder;
import com.appkubes.mall.restful.application.order.order.entity.OrderStateEnum;
import com.appkubes.mall.restful.application.order.order.entity.vo.OrderVo;
import com.appkubes.mall.restful.application.order.order.service.impl.OrderServiceImpl;
import com.appkubes.mall.restful.application.plugin.rent.service.PluginRentService;
import com.appkubes.mall.restful.application.wx.model.CreditModel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Jiahong Chen
 * @date 2019/11/9
 */
@EnableScheduling
@Configuration
@Slf4j
public class ScheduleConfig {

    @Resource
    OrderServiceImpl orderService;
    @Resource
    private OrderServiceImpl orderServiceImpl;
    @Resource
    PluginRentService pluginRentService;

//    @Scheduled(cron = "0 * * * * ? ")
//    public void orderCompeleted() {
//        System.out.println("订单租赁查询定时器启动");
//        log.info("订单租赁查询定时器启动");
//        MallOrder queryEntity = new MallOrder();
//        queryEntity.setStatus(OrderStateEnum.USING.value());
//        List<MallOrder> orderList = orderService.selectListByEntity(queryEntity);
//        log.info("订单租赁定时器正在执行。。。。。。,共有单：" + orderList.size());
//        orderList.forEach(order -> {
//            try {
//                JSONObject jsonObject = pluginRentService.getOrderState(order.getOrderKey());
//                System.out.println(jsonObject.toJSONString());
//                if (jsonObject.getString("buyStatus") == "2" || "OVER".equals(jsonObject.getString("status"))) {
//                    System.out.println("租赁订单完成：" + order.getOrderKey());
//                    order.setStatus(OrderStateEnum.COMPLETED.value());
//                    order.setUpdateTime(DateUtils.getCurrentTimestamp());
//                    orderServiceImpl.updateById(order);
//                }
//            } catch (Exception e) {
//                System.out.println(e.getMessage());
//            }
//        });
//    }

    @Scheduled(cron = "0 * * * * ? ")
    public void orderTimeOut() {
        try {
            System.out.println("订单超时定时器启动");
            log.info("订单超时定时器启动");
            Long greatTime = new Date().getTime() / 1000;

            QueryWrapper<MallOrder> queryWrapper = new QueryWrapper<>();
            MallOrder queryOrder = new MallOrder();
            queryOrder.setStatus(OrderStateEnum.UNPAY.value());
            queryWrapper.setEntity(queryOrder);
            queryWrapper.le("expire_time", greatTime.intValue());


            List<MallOrder> orderList = orderService.getBaseMapper().selectList(queryWrapper);
            log.info("订单超时定时器正在执行。。。。。。,共有单：" + orderList.size());
            orderList.forEach(order -> {
                log.info("该订单超时：" + order.getOrderNo());
                order.setStatus(OrderStateEnum.CANCEL.value());
                order.setCancelTime(greatTime.intValue());
                order.setUpdateTime(greatTime.intValue());
                order.setMsg("订单超时关闭");
                order.setUpdateTime(DateUtils.getCurrentTimestamp());
                orderServiceImpl.updateById(order);

                if ("RENT".equals(order.getFlexType()) && !"1".equals(order.getFlexSegment2())) {
                    CreditModel model = new CreditModel();
                    model.setUserKey(order.getUserKey());
                    model.setOrderKey(order.getFlexSegment1());
                    try {
                        //TODO 需要考虑分布式异步事务
                        try {
                            orderServiceImpl.cancel(order.getOrderKey());
                        } catch (Exception e) {

                        }
                        try {
                            pluginRentService.cancelZuLinOrder(model);
                        } catch (Exception e) {

                        }
                    } catch (Exception e) {
                        log.info(e.getMessage() + ",订单号：" + order.getOrderKey() + "，用户key:" + order.getUserKey());
                    }
                } else {
                    try {
                        orderServiceImpl.cancel(order.getOrderKey());
                    } catch (Exception e) {
                        log.info(e.getMessage() + ",订单号：" + order.getOrderKey() + "，用户key:" + order.getUserKey());
                    }
                }
            });
            log.info("订单超时定时器执行完成");
        } catch (Exception e) {
            log.error("订单超时定时器错误", e);
        }
    }

    @Scheduled(cron = "0 0 * * * ? ")
    public void orderUsing() {
        try {
            System.out.println("订单自动收货定时器启动");
            log.info("订单自动收货定时器启动");
            Long greatTime = new Date().getTime() / 1000;

            QueryWrapper<MallOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.le("expire_time", greatTime.intValue());
            queryWrapper.in("status", Arrays.asList(OrderStateEnum.SENDING.value()));

            List<MallOrder> orderList = orderService.getBaseMapper().selectList(queryWrapper);
            log.info("订单自动收货定时器正在执行。。。。。。,共有单：" + orderList.size());
            orderList.forEach(order -> {
                log.info("该订单自动收货：" + order.getOrderNo());
                OrderVo orderVo = new OrderVo();
                orderVo.setOrderKey(order.getOrderKey());
                orderService.usingOrder(orderVo);
            });
            log.info("订单自动收货定时器执行完成");
        } catch (Exception e) {
            log.error("订单超时定时器错误", e);
        }
    }
}
